/*
 * UIListarEscuelas.java
 *
 * Created on 25 de enero de 2008, 10:50
 */

package vista;

import controlador.CListar;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import negocios.Escuela;

/**
 *
 * @author  marcelo gonzalez
 */
public class UIListarEscuelas extends javax.swing.JFrame 
{
    private Collection escuelas = new ArrayList();
    private UIEscuelas es = new UIEscuelas();
    private UIMatriculados matriculados = new UIMatriculados();
    private String origen = "";
    
    /** Creates new form UIListarEscuelas */
    public UIListarEscuelas() 
    {
        initComponents();
        this.es = es;
        Dimension pantalla, cuadro;
	pantalla = Toolkit.getDefaultToolkit().getScreenSize();
	cuadro = this.getSize();
	this.setLocation(((pantalla.width - cuadro.width)/2), (pantalla.height - cuadro.height)/2);
        this.ajustarColumnas();
    }
    
    public UIListarEscuelas(UIEscuelas es) 
    {
        initComponents();
        this.es = es;
        this.origen = "ESCUELAS";
        Dimension pantalla, cuadro;
	pantalla = Toolkit.getDefaultToolkit().getScreenSize();
	cuadro = this.getSize();
	this.setLocation(((pantalla.width - cuadro.width)/2), (pantalla.height - cuadro.height)/2);
        this.llenarTabla(new Escuela());
        this.ajustarColumnas();
    }
    
    public UIListarEscuelas(UIMatriculados matriculados) 
    {
        initComponents();
        this.matriculados = matriculados;
        this.origen = "MATRICULADOS";
        Dimension pantalla, cuadro;
	pantalla = Toolkit.getDefaultToolkit().getScreenSize();
	cuadro = this.getSize();
	this.setLocation(((pantalla.width - cuadro.width)/2), (pantalla.height - cuadro.height)/2);
        this.llenarTabla(new Escuela());
        this.ajustarColumnas();
    }
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jLNombre = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jBInsertar = new javax.swing.JButton();
        jBSalir = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JSeparator();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Insertar Escuela");
        setResizable(false);

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Codigo", "Nombre", "Localidad"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable1MouseClicked(evt);
            }
        });
        jTable1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jTable1KeyPressed(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);

        jLNombre.setBackground(new java.awt.Color(255, 255, 204));
        jLNombre.setText("Nombre");
        jLNombre.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        jLNombre.setOpaque(true);

        jTextField1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jTextField1KeyReleased(evt);
            }
        });

        jBInsertar.setText("Insertar");
        jBInsertar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBInsertarActionPerformed(evt);
            }
        });

        jBSalir.setText("Salir");
        jBSalir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBSalirActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(155, 155, 155)
                        .addComponent(jBInsertar, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jBSalir, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap(162, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jLNombre, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 261, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(110, 110, 110))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jSeparator1, javax.swing.GroupLayout.DEFAULT_SIZE, 517, Short.MAX_VALUE)
                        .addContainerGap())
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 517, Short.MAX_VALUE)
                        .addContainerGap())))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLNombre, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(17, 17, 17)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 158, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(5, 5, 5)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jBSalir, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jBInsertar, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {jBInsertar, jBSalir});

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jTextField1KeyReleased(java.awt.event.KeyEvent evt)//GEN-FIRST:event_jTextField1KeyReleased
    {//GEN-HEADEREND:event_jTextField1KeyReleased
// TODO add your handling code here:
        this.filtrar(this.jTextField1.getText().toUpperCase());
    }//GEN-LAST:event_jTextField1KeyReleased

    private void jBInsertarActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jBInsertarActionPerformed
    {//GEN-HEADEREND:event_jBInsertarActionPerformed
// TODO add your handling code here:
        this.insertar(this.jTable1.getSelectedRow());
    }//GEN-LAST:event_jBInsertarActionPerformed

    private void jBSalirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBSalirActionPerformed
// TODO add your handling code here:
        this.dispose();
    }//GEN-LAST:event_jBSalirActionPerformed

    private void jTable1KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTable1KeyPressed
// TODO add your handling code here:
        if(evt.getKeyCode()==27)
            this.dispose();
    }//GEN-LAST:event_jTable1KeyPressed

    private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked
// cuando se seleccione una fila, los datos de esa fila deben aparecer en los textbox de abajo solo si no se desea guardar un nuevo elemento
        
        
    }//GEN-LAST:event_jTable1MouseClicked
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new UIListarEscuelas().setVisible(true);
            }
        });
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jBInsertar;
    private javax.swing.JButton jBSalir;
    private javax.swing.JLabel jLNombre;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration//GEN-END:variables
    
    
    private void llenarTabla(Escuela e)
    {
        CListar listar = new CListar();
        this.escuelas = listar.hacerListado(e);
        listar = null;
        Iterator it = escuelas.iterator();
        // ahora obtengo el modelo de la tabla
        DefaultTableModel modelo = (DefaultTableModel)this.jTable1.getModel();
        String datos[] = new String[3];
        while(it.hasNext())
        {
            e = (Escuela)it.next();
            datos[0] = String.valueOf(e.getIdescuela()).trim();
            datos[1] = e.getNombre().trim();
            datos[2] = e.getLocalidad().getNombre().trim();
            modelo.addRow(datos);
        }
    }
    
    private void insertar(int fila)
    {
        if(fila < 0)
            JOptionPane.showMessageDialog(null,"Debe seleccionar una escuela","Error",JOptionPane.ERROR_MESSAGE);
        else
        {
            Iterator it = escuelas.iterator();
            Escuela e = new Escuela();
            while(it.hasNext()) 
            {
                e = (Escuela)it.next();
                if(e.getIdescuela() == Integer.parseInt(String.valueOf(this.jTable1.getValueAt(this.jTable1.getSelectedRow(),0))))
                {
                    if(this.origen.equals("ESCUELAS"))
                        this.es.insertar(e);
                    if(this.origen.equals("MATRICULADOS"))
                        this.matriculados.insertar(e);
                    this.dispose();
                }
            }
        }
        
    }
    
    private void filtrar(String cadena)
    {
        // de alguna forma mando la cadena para que otro objeto me devuelva una nueva coleccion con los barrios filtrados
        //barrios = algo(cadena);
        // solo queda limpiar la tabla y volverla a cargar
        this.limpiar();
        Escuela e = new Escuela();
        e.setNombre(cadena);
        this.llenarTabla(e);
    }
    
    private void limpiar()
    {
        DefaultTableModel modelo = (DefaultTableModel)this.jTable1.getModel();
        while(this.jTable1.getRowCount() != 0)
                modelo.removeRow(0);
        modelo = null;
    }
    
    private void ajustarColumnas()
     {
         TableColumn column = null;
         for (int i = 0; i < 3; i++) 
        {
            column = jTable1.getColumnModel().getColumn(i);
            switch(i)
            {
                case 0:
                        column.setPreferredWidth(15);
                        break;
                case 1:
                        column.setPreferredWidth(199);
                        break;
                case 2:
                        column.setPreferredWidth(167); 
                        break;
            }
        }
     }
}
